package com.vornitologist.widgetset.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VConsole;

/**
 * This is a simple application cache monitor. It also notifies demo users when
 * offline mode is ready to be used.
 */
public class CacheManifestStatusIndicator implements EntryPoint {

	private static final int UNCACHED = 0;
	private static final int IDLE = 1;
	private static final int CHECKING = 2;
	private static final int DOWNLOADING = 3;
	private static final int UPDATEREADY = 4;
	private static final int OBSOLETE = 5;

	private Element progressElement;
	private int uncachedcount = 0;

	public void init() {
		hookCachedListener();
		Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
			public boolean execute() {
				VConsole.error("Cache status " + getStatus());
				switch (getStatus()) {
				case UNCACHED:
					uncachedcount++;
					return uncachedcount < 100;
				case CHECKING:
				case DOWNLOADING:
					showProgress();
					return true;
				case IDLE:
					hideProgress();
					return false;
				case UPDATEREADY:
					requestUpdate();
				default:
					return false;
				}
			}
		}, 500);
	}

	protected void showProgress() {
		Util.browserDebugger();
		if (progressElement == null) {
			progressElement = Document.get().createDivElement();
			progressElement.addClassName("v-cache-loading-indicator");
		}
		RootPanel.getBodyElement().appendChild(progressElement);
	}

	protected void requestUpdate() {
		if (Window
				.confirm("There are updates ready to be installed. Would you like to restart now?")) {
			Window.Location.reload();
		} else {
			hideProgress();
		}
	}

	protected void hideProgress() {
		progressElement.removeFromParent();
	}

	private static final native int hookCachedListener()
	/*-{
	    $wnd.applicationCache.addEventListener('cached', function() { alert("Resources required for offline mode demo are now loaded to your device. You can now restart the application without network connection."); }, false);
	}-*/;

	private static final native int getStatus()
	/*-{
	    return $wnd.applicationCache.status;
	}-*/;

	public void onModuleLoad() {
		new CacheManifestStatusIndicator().init();
	}

}
